package top.honlnk.common.network;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import top.honlnk.common.constant.UserConstant;
import top.honlnk.common.exception.CustomException;
import top.honlnk.pojo.entity.OcrAdminInfo;

import java.io.IOException;

@Slf4j
public class GetOCRAccessTokenNetwork {


    public String getOCRAccessToken(@NotNull OcrAdminInfo ocrAdminInfo) {
       // 目标URL
        String url = "https://aip.baidubce.com/oauth/2.0/token" +
                "?grant_type=client_credentials" +
                "&client_id=" + ocrAdminInfo.getApiKey() +
                "&client_secret=" + ocrAdminInfo.getSecretKey();

        JSONObject responseObject;

        String accessToken = null;


        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost请求
            HttpPost httpPost = new HttpPost(url);

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 检查响应状态码
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 读取并响应内容
                    HttpEntity responseEntity = response.getEntity();
                    if (responseEntity != null) {
                        String responseString = EntityUtils.toString(responseEntity, "UTF-8");
                        // 将 responseString 解析为一个 JSONObject 对象并赋值给 responseObject，便于后续处理 JSON 数据。
                        responseObject = new JSONObject(responseString);
                        // 判断返回结果中是否有错误码，并根据错误码进行相应的处理
                        if (responseObject.has("error") && responseObject.getString("error").equals("invalid_client")) {
                            throw new CustomException("无效客户端：" + responseObject.getString("error_description"));
                        }
                        if (responseObject.has("access_token")) {
                            accessToken = responseObject.getString("access_token");
                            log.info("获取访问令牌成功，访问令牌：{}", accessToken);
                        }
                    }
                } else {
                    log.error(UserConstant.REQUEST_FAIL_LOG, response.getStatusLine().getStatusCode());
                    log.error(UserConstant.RESPONSE_BODY, response);
                    throw new CustomException(UserConstant.REQUEST_FAIL + response.getStatusLine().getStatusCode());
                }
            } catch (JSONException e) {
                log.error("JSON解析错误", e);
                throw new CustomException(e.getMessage());
            }
        } catch (IOException e) {
            log.error("向后端服务发送请求时出错。", e);
            throw new CustomException(e.getMessage());
        }
       return accessToken;
    }
}
